//-----------------------------------------------------------------------------
// File: Startup.cs
//
// Copyright (c) Dmitry Shuklin. All rights reserved.
//-----------------------------------------------------------------------------
using System;

namespace Cerebrum.DesktopClient
{
	/// <summary>
	/// Summary description for Startup.
	/// </summary>
	public sealed class Startup
	{
		private Startup()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		[STAThread]
		static void Main() 
		{
			System.Threading.Mutex myMutex = null;
			try
			{
				ObjectiveDraw.SplashScreen dlg = new ObjectiveDraw.SplashScreen();
				dlg.Show();
				dlg.Refresh();
				ObjectiveDraw.Platform.Application.SplashScreen = dlg;


				System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
#if !DEBUG
				// Mutex constructor sets ownsMutex to false if mutex already exists,
				//    or to true if a new mutex was just created
				bool ownsMutex;
				myMutex = new System.Threading.Mutex(false, System.Windows.Forms.Application.ProductName, out ownsMutex);
				if (!ownsMutex)
				{
					//System.Resources.ResourceManager resources = new System.Resources.ResourceManager("Cerebrum.DesktopEngine.Resources", typeof(Cerebrum.DesktopEngine.BackgroundListener).Assembly);
					//System.Windows.Forms.MessageBox.Show(((string)(resources.GetObject("ApplicationAlreadyRunning.Message"))));
					System.Windows.Forms.MessageBox.Show("Objective Draw is already running", "Objective Draw");
					return;
				}
				GC.KeepAlive(myMutex);
#endif

				try
				{
					string cultureName = ((string)(configurationAppSettings.GetValue("DesktopClient.Culture", typeof(string))));
					if(cultureName!=null)
					{
						System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cultureName);
					}
				}
				catch
				{
				}

				bool quickNotifyIconEnable = true;
				try
				{
					quickNotifyIconEnable = ((bool)(configurationAppSettings.GetValue("QuickNotifyIcon.Enabled", typeof(bool))));
				}
				catch
				{
				}

				Cerebrum.DesktopEngine.Application.Run(quickNotifyIconEnable, typeof(Cerebrum.DesktopEngine.Application), typeof(Cerebrum.Integrator.DomainContext), typeof(Cerebrum.DesktopEngine.PrimaryWindowForm));
			}
			catch(System.Exception ex)
			{
				try
				{
					if(ObjectiveDraw.Platform.Application.SplashScreen!=null)
					{
						ObjectiveDraw.Platform.Application.SplashScreen.Close();
						ObjectiveDraw.Platform.Application.SplashScreen = null;
					}
				}
				catch
				{
				}
				System.Windows.Forms.MessageBox.Show(ex.ToString(), "Critical Error: " + ex.Source, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
			}
			finally
			{
				// be sure and release Mutex before program exits
				if (myMutex != null) myMutex.Close();
			}
		}

	}
}
